<template>
  <div id="purchaseOrders">
    <search-form
      ref="search"
      :type="0"
      @handleSearch="handleSearch"
    ></search-form>
    <div class="table-main">
      <div class="empty-header" v-show="activeHeader"></div>
      <!--   -->
      <div class="table-header" :class="[activeHeader ? 'active-header' : '']">
        <span class="title">
          采购单{{ total === 0 ? "" : "（" + total + "）" }}
        </span>
        <div class="action-bar">
          <el-tooltip
            :value="isSelection"
            manual
            content="请勾选需要确认的采购单"
            placement="bottom"
            effect="light"
          >
            <el-button size="mini" @click="handleConfirm" plain>确认</el-button>
          </el-tooltip>
          <el-upload
          v-show="showBtn"
            class="upload-demo"
            :action="uploadUrl"
            multiple
            :show-file-list="false"
            :on-success="handleSuccess"
            :on-error="handleError"
          >
            <el-button size="mini" plain>导入</el-button>
          </el-upload>
          <el-button v-show="false" size="mini" style="margin-left:10px;" plain disabled
            >批量导入处理</el-button
          >
          <el-dropdown
          v-show="showBtn"
            size="mini"
            class="export-dropdown"
            style="margin:0 10px;"
            @command="handleExport"
            placement="bottom-start"
          >
            <el-button size="mini" @click="handleExport('/purchases/excel')">
              导出<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="/purchases/excel"
                >导出列表</el-dropdown-item
              >
              <el-dropdown-item command="/purchase-items/excel"
                >导出明细</el-dropdown-item
              >
            </el-dropdown-menu>
          </el-dropdown>
          <!-- <el-button size="mini" plain @click="handleExport">导出</el-button> -->
          <el-button
            size="mini"
            icon="el-icon-setting"
            plain
            disabled
            style="margin-left:10px;"
          ></el-button>
        </div>
      </div>
      <el-table
        :data="tableData"
        border
        :fit="true"
        style="width: 100%;"
        highlight-current-row
        @selection-change="handleSelectionChange"
        border
        stripe
        :header-cell-style="{
          color: '#333',
          fontSize: '12px',
          background: '#eee',
          fontWeight: '700'
        }"
      >
        <el-table-column
          class="setNmae"
          type="selection"
          align="center"
          width="55"
        >
        </el-table-column>
        <el-table-column
          class="setNmae"
          v-for="(item, index) in headers"
          :label="item.label"
          :key="index"
          :fixed="item.fixed"
          :width="item.width"
        >
          <template slot-scope="scope">
            <template v-if="'time1,time2'.includes(item.prop)">
              <span>{{
                common.dateFmt(scope.row[item.prop], "yyyy-MM-dd hh:mm:ss")
              }}</span>
            </template>
            <template v-else-if="'expirationDate'.includes(item.prop)">
              <span>{{
                common.dateFmt(scope.row[item.prop], "yyyy-MM-dd") + " 23:59:59"
              }}</span>
            </template>
            <template v-else-if="'purchaseNo'.includes(item.prop)">
              <el-link
                :underline="false"
                type="primary"
                @click="toPath(scope.row)"
                >{{ scope.row[item.prop] }}</el-link
              >
              <p>经营模式：{{ scope.row["operationMode"] }}</p>
              <p>单据类型：{{ scope.row["orderType"] }}</p>
            </template>
            <template v-else-if="'channelName'.includes(item.prop)">
              <p>来源类型：补货越库</p>
              <p>来源单号：{{ scope.row["channelId"] }}</p>
              <p>合同编号：{{ scope.row["contractNo"] }}</p>
            </template>
            <template v-else-if="'providerName'.includes(item.prop)">
              <p>{{ scope.row[item.prop] }}</p>
              <p>{{ scope.row["providerNo"] }}</p>
            </template>
            <template v-else-if="'storageName'.includes(item.prop)">
              <p>{{ scope.row[item.prop] }}</p>
              <p>{{ scope.row["storageNo"] }}</p>
            </template>
            <template v-else-if="'amount'.includes(item.prop)">
              <p>币种：CNY(人民币)</p>
              <p>金额：{{ scope.row[item.prop].toFixed(2) }}</p>
            </template>
            <template v-else-if="'quantity'.includes(item.prop)">
              <p>SKU个数: :{{ scope.row["variety"] }}</p>
              <p>下单数量：{{ scope.row[item.prop] }}</p>
              <p>到货数量：{{ scope.row["count01"] }}</p>
            </template>
            <template v-else-if="'storageType'.includes(item.prop)">
              <span>散装</span>
            </template>
            <template v-else-if="'fhbz'.includes(item.prop)">
              <span>一单一发</span>
            </template>
            <template v-else-if="'purchaseStatus'.includes(item.prop)">
              <span>{{ scope.row["appointmentNo"] ? "已预约" : "" }}</span>
            </template>
            <template v-else-if="'zdcjfhd'.includes(item.prop)">
              <span>否</span>
            </template>
            <template v-else>
              <span>{{ scope.row[item.prop] }}</span>
            </template>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="状态/审核人" width="102">
          <template slot-scope="scope">
            <span>{{ scope.row["purchaseStatus"] }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="120">
          <template slot-scope="scope">
            <el-link
              :underline="false"
              type="primary"
              @click="toPath(scope.row)"
              >详情</el-link
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="bottom-page">
        <div class="scroll-table-wrapper">
          <div class="scrollbar-inner" :style="{ width: scrollBarWidth }"></div>
        </div>
        <Pagination
          :total="total"
          :pageData="page"
          @handlePageChange="handlePageChange"
        ></Pagination>
      </div>
    </div>
  </div>
</template>

<script>
import SearchForm from "@/components/SearchForm/";
import { headers } from "./config";
const page = () => {
  return {
    page: 1,
    size: 10
  };
};
export default {
  name: "purchaseOrders",
  components: { SearchForm },
  data() {
    return {
      page: page(),
      total: 0, // 总条数
      tableData: [],
      headers,
      selections: [],
      isSelection: false,
      uploadUrl: `/api/purchases/excel`,
      form: {},
      distance_header: 0,
      activeHeader: false,
      scrollBarWidth: "2000px",
      orderScrolled:0
    };
  },
  created() {
    this.init();
  },
  mounted() {
    this.createDom()
  },
  activated() {
    this.onScroll(this.orderScrolled)
  },
  computed:{
    showBtn(){
      return this.$store.state.app.showBtn
    }
  },
  watch: {
    activeHeader: function(newVal, oldVal) {
      this.setTop(newVal);
    }
  },
  methods: {
    createDom() {
      // 一次性计算赋值，减少滚动计算节点位置次数
      let header = document.querySelector(".table-header");
      let par = document.querySelector(".table-header").offsetParent;
      if (par.nodeName.toLowerCase() == "body") {
        this.distance_header = header.offsetTop;
      } else {
        while (par) {
          this.distance_header += par.offsetTop;
          par = par.offsetParent;
        }
      }
      if (this.distance_header != 0) {
        this.distance_header -= 72;
      }
      this.$nextTick(function() {
        document
          .querySelector("#purchaseOrders")
          .addEventListener("scroll", this.onScroll);
        document
          .querySelector(".scroll-table-wrapper")
          .addEventListener("scroll", this.setLeft);
        const ele = document.querySelector(".el-table__body");
        this.scrollBarWidth = window.getComputedStyle(ele).width;
      });
      window.addEventListener("scroll", this.onScroll, true);
    },
    setLeft() {
      const scrollLeft = document.querySelector(".scroll-table-wrapper")
        .scrollLeft;
      document.querySelector(".el-table__body-wrapper").scrollLeft = scrollLeft;
    },
    setTop(val) {
      if(this.$route.name == 'purchaseOrders'){
        var dom = document.querySelector(".el-table__header-wrapper");
        var dom1 = document.querySelector(
          ".el-table__fixed .el-table__fixed-header-wrapper"
        ); //左边
        var dom1Body = document.querySelector(
          ".el-table__fixed .el-table__fixed-body-wrapper"
        );

        var dom2 = document.querySelector(
          ".el-table__fixed-right .el-table__fixed-header-wrapper"
        );
        var dom2Body = document.querySelector(
          ".el-table__fixed-right .el-table__fixed-body-wrapper"
        );

        var wid =
          document.querySelector(".el-table__fixed-header-wrapper").offsetWidth -
          220;
        var dom2header = document.querySelector(
          ".el-table__fixed-right .el-table__header"
        );
        if (val) {
          dom.classList.add("positiheader2");
          dom1.classList.add("positiheader");
          dom1Body.classList.add("positiheader2body");
          dom2.classList.add("positiheader3");
          dom2Body.classList.add("positiheader2body");
          dom2header.style.marginLeft = -wid + "px";
        } else {
          dom.classList.remove("positiheader2");
          dom1Body.classList.remove("positiheader2body");
          dom1.classList.remove("positiheader");
          dom2.classList.remove("positiheader3");
          dom2Body.classList.remove("positiheader2body");
          dom2header.style.marginLeft = 0 + "px";
        }
      }
    },
    onScroll(aliveScroll) {
      if (this.$route.name == "purchaseOrders") {
        if(aliveScroll && !isNaN(aliveScroll)) {
          document.querySelector(".app-wrapper").scrollTop = aliveScroll
        }
        const scrolled = document.querySelector(".app-wrapper").scrollTop;
        this.orderScrolled = scrolled
        if (scrolled >= this.distance_header) {
          this.activeHeader = true;
        } else {
          this.activeHeader = false;
        }
      }
    },
    // 查询按钮事件
    handleSearch(form) {
      this.page = page();
      this.form = form;
      this.init();
    },
    // 分页
    handlePageChange(pages) {
      this.page = pages;
      this.init();
    },
    // 列表多选
    handleSelectionChange(element) {
      this.selections = element;
    },
    // 请求接口查询数据
    init() {
      const params = {
        size: this.page.size,
        page: this.page.page <= 0 ? 0 : this.page.page - 1,
        ...this.form,
        sort: "id"
      };
      this.$http("/purchases", params).then(res => {
        this.tableData = res.records ? res.records : [];
        this.total = isNaN(res.totalElements) ? 0 : Number(res.totalElements);
      });
    },
    // 导出
    handleExport(ApiUrl) {
      let params = {
        ...this.page,
        page:this.page.page - 1
      };
      let arr = []
      if (this.selections.length > 0) {
          arr = this.selections.map(item => {
            return item.purchaseNo;
          });
          if (ApiUrl == "/purchases/excel") {
            params.purchaseNosStr = arr.join(",");
          }
      } else {
        arr = this.tableData.map(item => {
          return item.purchaseNo;
        });
      }
      if (ApiUrl == "/purchase-items/excel") {
        params.purchaseNosStr = arr.join(",");
      }
      console.log(params, 'params');
      window.open(
        "http://web.tmall.pingyee.com.cn" +
          ApiUrl +
          "?" +
          this.common.createUrl(params)
      );
    },
    // 进度条回调函数
    /* progressBar(progressEvent) {
      // 获取百分比（此处保留了一位小数）
      let percentage = Number((progressEvent.loaded / progressEvent.total * 100).toFixed(1));
      console.log(percentage, 'percentage')
    }, */
    // 确定按钮
    handleConfirm() {
      if (this.selections.length <= 0) {
        this.isSelection = true;
        setTimeout(() => {
          this.isSelection = false;
        }, 2000);
      } else {
        this.isSelection = false;
      }
    },
    // 导入后 成功&失败 回调
    handleSuccess(res) {
      this.$message({
        message: "导入成功！",
        type: "success",
        offset: 100
      });
    },
    handleError(err) {
      this.$message({
        message: "导入失败！",
        type: "error",
        offset: 100
      });
    },
    toPath(row) {
      this.$router.push({ path: "/purchaseOrderDetails", query: { ...row } });
    }
  }
};
</script>

<style lang="scss" scoped>
.table-main {
  margin: 12px;
  background-color: #fff;
  font-size: 12px;
  position: relative;
  padding-bottom: 45px;
  overflow: hidden;
  .empty-header {
    height: 50px;
    padding: 0 10px;
  }
  .table-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 50px;
    padding: 0 10px;
    .title {
      font-size: 16px;
    }
  }
  .active-header {
    position: fixed;
    top: 72px;
    left: 196px;
    right: 29px;
    background-color: #fff;
    z-index: 200;
  }
  .upload-demo {
    display: inline-block;
    margin-left: 10px;
  }
  .bottom-page {
    position: fixed;
    bottom: 0;
    background-color: #fff;
    z-index: 200;
    left: 196px;
    right: 29px;
  }
  .scroll-table-wrapper {
    overflow-x: auto;
    overflow-y: hidden;
    bottom: 0;
    z-index: 1;
    display: block;
    margin-top: -18px;
    .scrollbar-inner {
      height: 1px;
      visibility: hidden;
    }
  }
}
</style>

<style scoped>
.table-main >>> .el-table__body,
.table-main >>> .el-table__body p {
  font-size: 12px;
}
.table-main >>> .el-table .cell {
  line-height: 14px;
}
.table-main >>> .el-table td,
.table-main >>> .el-table th {
  padding: 8px 0;
  border-color: #e3e3e3;
}
.table-main >>> .el-dropdown__caret-button {
  background-color: #fff !important;
}
/* .table-main >>> .el-dropdown-selfdefine {
  border-color: #00c900 !important;
  color: #00c900 !important;
  background-color:#fff !important;
} */
/* .active-header >>> .el-dropdown-menu {
  top: 98px !important;
}
.el-dropdown-menu {
  top: 300px !important;
} */
.el-dropdown-menu__item {
  padding: 0 12px !important;
}
.popper__arrow {
  display: none !important;
}
</style>
